import type { FcPageConfig } from '@/types/fcform'
import type { ActionItem } from '@/types/hooks/useTable'
import type { ConfigState } from '@/types/hooks/useEdit'
import { useApi } from '@/hooks/useApi.ts'
import { useEdit } from '@/hooks/useEdit.ts'
import { omit, pick } from 'lodash-es'

export interface ChangeOptions {
  key: string
  type: 'add' | 'edit' | 'del'
  params?
}

export interface ExtendedProps {
  /**
   * 自定义扩展对象
   * */
  options?: {
    [key: string]: unknown
  }
  /**
   * 添加或编辑成功回掉
   * */
  change?: (options: ChangeOptions) => void
}

export function useTable(pageConfig: FcPageConfig, extended: ExtendedProps = {}) {
  /**
   * table数据
   * */
  const table = useApi<Record<string, unknown>>({
    delKey: pageConfig.KEY || 'id',
    delSuccess: () => {
      extended?.change?.({
        type: 'del',
        key: 'del',
      })
    },
    ...omit(pageConfig.table, ['props']),
  })

  /**
   * 批量注册所有弹框
   * */
  const action = reactive<ActionItem>({})
  const updDefault = reactive({})
  Object.keys(pageConfig.edit || {}).forEach((key) => {
    const base = pageConfig.edit[key]
    let onShowCallback: () => void = () => {}
    const baseConfig: ConfigState = {
      ...omit(base, ['formConfig', 'table', 'gridConfig']),
      extended: {
        tableData: toRef(table.tableInfo, 'tableData'),
        onShow: (cb) => {
          onShowCallback = cb
        },
        ...extended?.options,
      },
      props: {
        formItems: [],
      },
    }
    if (base?.formConfig) {
      baseConfig.props.formConfig = base.formConfig
    }
    if (base?.gridConfig) {
      baseConfig.props.gridConfig = base.gridConfig
    }
    if (!baseConfig?.key) {
      baseConfig.key = pageConfig.KEY || 'id'
    }
    baseConfig.addChange = (params) => {
      if (table && key === 'default') {
        table.queryData()
      }
      extended?.change?.({
        type: 'add',
        key,
        params,
      })
    }
    baseConfig.editChange = (params) => {
      if (table && key === 'default') {
        table.fetchData()
      }
      extended?.change?.({
        type: 'edit',
        key,
        params,
      })
    }
    const res = useEdit(baseConfig)
    const originalOpen = res.open
    res.open = (...args: Parameters<typeof originalOpen>) => {
      originalOpen(...args)
      onShowCallback?.()
    }
    action[key] = res.open
    updDefault[key] = res.setDefaultValue
  })

  /**
   *  表格列表
   * */
  const tableProps = computed(() => {
    return {
      ...omit(pageConfig.pageProps, ['createSearchForm']),
      searchItems:
        pageConfig.pageProps?.createSearchForm?.({
          formData: toRef(table.tableInfo.queryForm),
          ...extended.options,
        }) ?? [],
      table: {
        key: pageConfig.KEY || 'id',
        columns: pageConfig.table.createColums({
          handDel: table.handDel,
          action: action,
          ...extended?.options,
        }),
        open: action.default,
        ...pick(table, ['handDel', 'queryData', 'handReset', 'YPagination']),
        props: {
          ...pageConfig.table?.props,
        },
      },
    }
  })

  const updateDefault = (key: 'default' | string, row: Record<string, unknown>) => {
    updDefault[key](row)
  }

  return {
    table,
    action,
    tableProps,
    updateDefault,
  }
}
